<template>
  <div class="caseContai">
    <el-icon>
        <aim />
      </el-icon>
    <h1>递归组件示例：</h1>
    <nest-menu :data="data" :activeIds="ids" @change="activeIdsChange" />
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ref } from "vue";
import NestMenu from "./NestMenu.vue";
import data from "./menu";
export default {
  name: "App",
  setup() {
    // const getSubIds = (child) => {
    //   const subIds = [];
    //   const traverse = (data) => {
    //     if (data && data.length) {
    //       const first = data[0];
    //       subIds.push(first.id);
    //       traverse(first._child);
    //     }
    //   };
    //   traverse(child);
    //   return subIds;
    // };
    // 假设默认选中 id 为 7
    const activeId = 7;
    const findPath = (menus, targetId) => {
      let ids;
      const traverse = (subMenus, prev) => {
        if (ids) {
          return;
        }
        if (!subMenus) {
          return;
        }
        subMenus.forEach((subMenu) => {
          if (subMenu.id === activeId) {
            ids = [...prev, activeId];
            return;
          }
          traverse(subMenu._child, [...prev, subMenu.id]);
        });
      };
      traverse(menus, []);
      return ids;
    };
    const ids = ref(findPath(data, activeId));
    const activeIdsChange = (newIds) => {
      ids.value = newIds;
      console.log("当前选中的id路径", newIds);
    };
    return {
      ids,
      activeIdsChange,
      data,
    };
  },
  components: {
    NestMenu,
  },
};
</script>

<style lang="scss">
.caseContai {
  padding: 20px;
  min-width: 800px;
}
</style>